#!/bin/bash

################################################################################
# verify_output.sh - Validation Script for Generated C++ Code
#
# This script validates the output of the C# to C++ conversion pipeline:
# 1. Checks if generated C++ files exist
# 2. Verifies file structure and naming
# 3. Attempts to compile generated C++ (if compiler available)
# 4. Reports validation results
#
# Usage:
#   ./verify_output.sh
################################################################################

set -e  # Exit on error (but we'll handle errors explicitly)

# Color codes for output
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Counters
PASS=0
FAIL=0
WARN=0

echo "================================================================================"
echo "C++ CODE VALIDATION REPORT"
echo "================================================================================"
echo ""

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OUTPUT_DIR="$SCRIPT_DIR/generated_cpp"

################################################################################
# Test 1: Check if generated_cpp directory exists
################################################################################
echo -e "${BLUE}[TEST 1]${NC} Checking generated_cpp directory..."
if [ -d "$OUTPUT_DIR" ]; then
    echo -e "${GREEN}✓ PASS${NC} - Directory exists: $OUTPUT_DIR"
    ((PASS++))
else
    echo -e "${RED}✗ FAIL${NC} - Directory not found: $OUTPUT_DIR"
    echo "  Run 'python run_full_pipeline.py' first to generate C++ code"
    ((FAIL++))
    exit 1
fi
echo ""

################################################################################
# Test 2: Count generated files
################################################################################
echo -e "${BLUE}[TEST 2]${NC} Counting generated files..."
HEADER_COUNT=$(find "$OUTPUT_DIR" -name "*.hpp" | wc -l)
SOURCE_COUNT=$(find "$OUTPUT_DIR" -name "*.cpp" | wc -l)

echo "  Headers (.hpp): $HEADER_COUNT"
echo "  Sources (.cpp): $SOURCE_COUNT"

if [ "$HEADER_COUNT" -gt 0 ] && [ "$SOURCE_COUNT" -gt 0 ]; then
    echo -e "${GREEN}✓ PASS${NC} - Found $HEADER_COUNT header(s) and $SOURCE_COUNT source file(s)"
    ((PASS++))
else
    echo -e "${RED}✗ FAIL${NC} - No C++ files generated"
    ((FAIL++))
    exit 1
fi
echo ""

################################################################################
# Test 3: Verify file naming conventions
################################################################################
echo -e "${BLUE}[TEST 3]${NC} Verifying file naming conventions..."
NAMING_OK=true

for file in "$OUTPUT_DIR"/*.hpp "$OUTPUT_DIR"/*.cpp; do
    if [ -f "$file" ]; then
        basename=$(basename "$file")

        # Check for lowercase snake_case naming
        if [[ ! "$basename" =~ ^[a-z_]+\.(hpp|cpp)$ ]]; then
            echo -e "${YELLOW}⚠ WARNING${NC} - File name not in snake_case: $basename"
            NAMING_OK=false
        fi
    fi
done

if $NAMING_OK; then
    echo -e "${GREEN}✓ PASS${NC} - All files follow snake_case naming convention"
    ((PASS++))
else
    echo -e "${YELLOW}⚠ WARNING${NC} - Some files don't follow snake_case convention"
    ((WARN++))
fi
echo ""

################################################################################
# Test 4: Check for required C++ constructs in headers
################################################################################
echo -e "${BLUE}[TEST 4]${NC} Checking header file contents..."
CONSTRUCT_OK=true

for header in "$OUTPUT_DIR"/*.hpp; do
    if [ -f "$header" ]; then
        basename=$(basename "$header")

        # Check for include guard or #pragma once
        if ! grep -q "#pragma once" "$header" && ! grep -q "#ifndef" "$header"; then
            echo -e "${RED}✗ FAIL${NC} - Missing include guard in: $basename"
            CONSTRUCT_OK=false
        fi

        # Check for namespace declaration
        if ! grep -q "namespace" "$header"; then
            echo -e "${YELLOW}⚠ WARNING${NC} - No namespace found in: $basename"
            CONSTRUCT_OK=false
        fi

        # Check for class declaration
        if ! grep -q "class" "$header"; then
            echo -e "${RED}✗ FAIL${NC} - No class declaration in: $basename"
            CONSTRUCT_OK=false
        fi
    fi
done

if $CONSTRUCT_OK; then
    echo -e "${GREEN}✓ PASS${NC} - All headers contain required C++ constructs"
    ((PASS++))
else
    echo -e "${RED}✗ FAIL${NC} - Some headers missing required constructs"
    ((FAIL++))
fi
echo ""

################################################################################
# Test 5: Check for required C++ constructs in source files
################################################################################
echo -e "${BLUE}[TEST 5]${NC} Checking source file contents..."
SOURCE_OK=true

for source in "$OUTPUT_DIR"/*.cpp; do
    if [ -f "$source" ]; then
        basename=$(basename "$source")

        # Check for corresponding header include
        header_name="${basename%.cpp}.hpp"
        if ! grep -q "#include.*$header_name" "$source"; then
            echo -e "${YELLOW}⚠ WARNING${NC} - Missing header include in: $basename"
            SOURCE_OK=false
        fi

        # Check for namespace declaration
        if ! grep -q "namespace" "$source"; then
            echo -e "${YELLOW}⚠ WARNING${NC} - No namespace found in: $basename"
        fi
    fi
done

if $SOURCE_OK; then
    echo -e "${GREEN}✓ PASS${NC} - All source files contain required includes"
    ((PASS++))
else
    echo -e "${YELLOW}⚠ WARNING${NC} - Some source files have issues"
    ((WARN++))
fi
echo ""

################################################################################
# Test 6: Attempt to compile generated C++ code
################################################################################
echo -e "${BLUE}[TEST 6]${NC} Attempting to compile generated C++ code..."

# Check for available C++ compiler
COMPILER=""
if command -v g++ &> /dev/null; then
    COMPILER="g++"
elif command -v clang++ &> /dev/null; then
    COMPILER="clang++"
else
    echo -e "${YELLOW}⚠ WARNING${NC} - No C++ compiler found (g++ or clang++)"
    echo "  Install g++ or clang++ to enable compilation testing"
    ((WARN++))
    COMPILER=""
fi

if [ -n "$COMPILER" ]; then
    echo "  Using compiler: $COMPILER"

    COMPILE_OK=true
    for source in "$OUTPUT_DIR"/*.cpp; do
        if [ -f "$source" ]; then
            basename=$(basename "$source")
            output_obj="${source%.cpp}.o"

            # Attempt compilation (syntax check only, no linking)
            if $COMPILER -std=c++20 -c -I"$OUTPUT_DIR" -fsyntax-only "$source" 2>/dev/null; then
                echo -e "  ${GREEN}✓${NC} $basename - syntax valid"
            else
                echo -e "  ${RED}✗${NC} $basename - compilation errors"
                COMPILE_OK=false

                # Show compilation errors
                echo "    Compilation output:"
                $COMPILER -std=c++20 -c -I"$OUTPUT_DIR" -fsyntax-only "$source" 2>&1 | head -10 | sed 's/^/    /'
            fi
        fi
    done

    if $COMPILE_OK; then
        echo -e "${GREEN}✓ PASS${NC} - All generated files compile successfully"
        ((PASS++))
    else
        echo -e "${RED}✗ FAIL${NC} - Some files have compilation errors"
        echo "  Note: This is expected for MVP - method stubs use 'throw std::runtime_error'"
        ((WARN++))
    fi
else
    echo "  Skipping compilation test (no compiler available)"
fi
echo ""

################################################################################
# Summary
################################################################################
echo "================================================================================"
echo "VALIDATION SUMMARY"
echo "================================================================================"
echo -e "${GREEN}Passed:${NC}   $PASS"
echo -e "${YELLOW}Warnings:${NC} $WARN"
echo -e "${RED}Failed:${NC}   $FAIL"
echo ""

if [ $FAIL -eq 0 ]; then
    echo -e "${GREEN}✅ VALIDATION SUCCESSFUL${NC}"
    echo ""
    echo "Generated C++ code structure is valid!"
    echo ""
    echo "Next steps:"
    echo "  1. Review generated files in: $OUTPUT_DIR"
    echo "  2. Implement method bodies (currently stubs)"
    echo "  3. Link with runtime shim library"
    exit 0
else
    echo -e "${RED}❌ VALIDATION FAILED${NC}"
    echo ""
    echo "Some validation checks failed. Review the output above."
    exit 1
fi
